﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands.Waimai
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class OrderInvoiceCommandHandler:BaseCommandHandler,IRequestHandler<OrderInvoiceCommand,BaseResult<string>>
    {
        private readonly IOrderBaseRepository _orderBaseRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderBaseRepository"></param>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        public OrderInvoiceCommandHandler(IOrderBaseRepository orderBaseRepository,INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _orderBaseRepository = orderBaseRepository;
        }

        public async Task<BaseResult<string>> Handle(OrderInvoiceCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var orderentity = await _orderBaseRepository.GetByOrderCodeAsync<ICasaMielSession>(request.OrderCode).ConfigureAwait(false);
            if (orderentity == null || orderentity.Mobile!=request.Mobile)
            {
                return new BaseResult<string>("", 9999, "订单不存在");
            }
            if (orderentity.PayMethod == 3)
            {
                return new BaseResult<string>("", 9999, "会员卡支付不开发票");
            }

            if (string.IsNullOrEmpty(orderentity.InvoiceUrl))
            {
                OrderLogger.Error($"开发票失败:{orderentity.OrderCode},{orderentity.CreateTime}");
                return new BaseResult<string>("", 9999, "开发票失败");
            }
            var url = "TakeOut/v1/Invoice/AddOrderInvoice";
            var data = new { request.Mobile,request.OrderCode,request.InvoiceId};
            var result = await PostThirdApiAsync<string>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
            return result;
        }
    }
}
